{% extends 'base.html' %}

{% block content %}
    <div class="form-group">
        <h2>上传吉他谱</h2>
        <form id="uploadForm" method="post" enctype="multipart/form-data">
            {% csrf_token %}
            <div class="form-group">
                <label for="name">吉他谱名称</label>
                <input type="text" id="name" name="name" class="form-control" placeholder="输入吉他谱名称" required>
            </div>

            <div class="form-group">
                <label for="author">作者</label>
                <input type="text" id="author" name="author" class="form-control" placeholder="输入作者名称" required>
            </div>

            <div class="form-group">
                <label for="type">类型</label>
                <select id="type" name="type" class="form-control">
                    <option value="1">弹唱</option>
                    <option value="2">指弹</option>
                </select>
            </div>

            <div class="form-group">
                <label for="cover_path">封面路径</label>
                <input type="text" id="cover_path" name="cover_path" class="form-control" placeholder="输入封面路径链接"
                       required>
            </div>

            <div id="image-upload-container" class="form-group">
                <label for="images">上传图片</label>
                <div class="image-upload">
                    <input type="file" id="images" name="images" class="form-control d-none" accept="image/*" multiple
                           onchange="uploadAndPreviewImages(event)">
                    <button type="button" class="btn btn-outline-primary add-image-btn" onclick="triggerFileInput()">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#ffffff" width="48px"
                             height="48px">
                            <path d="M19 15v4H5v-4H3v4a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-4h-2zM11 10.414V18h2v-7.586l3.293 3.293 1.414-1.414L12 5.586 6.293 12.293l1.414 1.414L11 10.414z"/>
                        </svg>
                    </button>
                </div>
            </div>

            <button type="button" onclick="submitForm()" class="btn btn-primary btn-block">上传</button>
        </form>
    </div>

    <script>
        let filePaths = []; // 用于存储上传的文件路径

        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        function deleteImage(save_path, previewDiv) {
            console.log("删除时获取到的地址===", save_path)
            // 创建 FormData 对象
            let formData = new FormData();
            formData.append('path', save_path);

            // 发送删除请求到后端
            fetch('/guitar/delete_file/', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': csrftoken  // 添加 CSRF 令牌到请求头
                }
            })
                .then(response => response.json())
                .then(data => {
                    if (data.message === '删除成功') {
                        console.log("save_path===", save_path);
                        // 从页面中移除图片预览
                        previewDiv.parentNode.removeChild(previewDiv);
                        // 从 filePaths 中移除对应的路径
                        filePaths = filePaths.filter(path => path !== save_path);
                        console.log('删除后的文件列表:', filePaths);

                    } else {
                        alert('删除失败: ' + data.error);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('发生了意外错误。');
                });
        }

        const csrftoken = getCookie('csrftoken');

        function triggerFileInput() {
            document.getElementById('images').click();
        }

        function uploadAndPreviewImages(event) {
            const files = event.target.files;

            Array.from(files).forEach((file) => {
                uploadFile(file);
            });
        }

        function uploadFile(file) {
            let formData = new FormData();
            formData.append('images', file);

            fetch('/guitar/upload_file/', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': csrftoken  // 添加 CSRF 令牌到请求头
                }
            })
                .then(response => response.json())
                .then(data => {
                    if (data.message === '上传成功') {
                        console.log("上传返回的路径：", data.save_path);
                        filePaths.push(data.save_path); // 保存路径到列表
                        previewImage(data.web_path, data.save_path);
                    } else {
                        alert('文件上传失败: ' + data.error);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('发生了意外错误。');
                });
        }

        function previewImage(web_path, save_path) {
            const container = document.getElementById('image-upload-container');

            const previewDiv = document.createElement('div');
            previewDiv.className = 'image-preview';

            const img = document.createElement('img');
            img.src = web_path;
            img.alt = "预览图片";
            img.className = "img-thumbnail";

            const deleteBtn = document.createElement('button');
            deleteBtn.type = 'button';
            deleteBtn.className = 'btn btn-danger delete-image-btn';
            deleteBtn.innerHTML = '删除';
            deleteBtn.onclick = function () {
                deleteImage(save_path, previewDiv);
            };

            previewDiv.appendChild(img);
            previewDiv.appendChild(deleteBtn);
            container.appendChild(previewDiv);
        }

        function submitForm() {
            let formData = new FormData();
            formData.append('name', document.getElementById('name').value);
            formData.append('author', document.getElementById('author').value);
            formData.append('type', document.getElementById('type').value);
            formData.append('cover_path', document.getElementById('cover_path').value);

            filePaths.forEach((path) => {
                formData.append('file_paths', path);
            });

            fetch('/guitar/upload_guitar_tab/', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': csrftoken  // 添加 CSRF 令牌到请求头
                }
            })
                .then(response => response.json())
                .then(data => {
                    if (data.message === '上传成功') {
                        alert('信息保存成功！');
                    } else {
                        alert('信息保存失败: ' + data.error);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('发生了意外错误。');
                });
        }
    </script>

    <style>
        .add-image-btn {
            display: inline-block;
            margin-top: 10px;
            background-color: transparent;
            border: none;
            cursor: pointer;
        }

        .image-preview {
            display: inline-block;
            position: relative;
            margin-right: 10px;
            margin-top: 10px;
        }

        .image-preview img {
            max-width: 100px;
            max-height: 100px;
        }

        .delete-image-btn {
            position: absolute;
            top: -10px;
            right: -10px;
            font-size: 12px;
            padding: 5px;
            border-radius: 50%;
        }
    </style>
{% endblock %}
